<?php

class Suami_istri extends Controller {

	function Suami_istri() {
		parent::Controller();
        $this->load->model('Sutri_model', 'p');
	}
	
	function index() {
        
		if (!$this->session->userdata('username')) {
			$data['isLogin'] = FALSE;
        	redirect("/login", "location");
		} else {
			$data['isLogin'] = TRUE;
			$data['username'] = $this->session->userdata('username');
			$data['role'] = $this->session->userdata('role');
		}

    	$list_nip = $this->_getNIP();
    	if ($list_nip<>'') {
    		$auto_jurusan = '$("#nip").autocompleteArray(['.$list_nip.'], {delay:10,minChars:1,matchSubset:1,cacheLength:10,maxItemsToShow:10});'; 
    	}
		$data['additional_js'] = '
		<script type="text/javascript">
        	$(function() {
		        $("#nip").focus();'.
		        $auto_jurusan.
			'});		        
		function deleteRow(id) {
			var txt = \'Anda yakin mau menghapus data ini?<input type="hidden" id="row-id" name="row-id" value="\'+ id +\'" />\';
				url = "'.base_url().'index.php/suami_istri/hapus/"+id;
			 $.ajax({
			   type: "POST",
			   url: "'.base_url().'index.php/suami_istri/bisa_dihapus/"+id,
			   success: function(msg) {
				 if (msg==\'bisa\') {
					$.prompt(txt,{
						buttons:{Hapus:true, Batal:false},
						callback: function(v){
							if(v) {
								$("tr#row-"+id).fadeOut("slow", function() {
									$("tr#row-"+id).remove();
								});
								$.post(url);
							}
						}
					});
				 } else {
					alert(\'Maaf, data tidak dapat dihapus dikarenakan terkait dengan data lain.\');
				 }
		       }
		    });
		}
		</script>
		';
		
		$data['judul'] = 'RIWAYAT DATA SUAMI ISTRI';
        if( $data['role'] == 0)
            $nip = $this->session->userdata('nip');
        else if ($this->uri->segment(3) == 'nip')
            $nip = $this->uri->segment(4);
        else
		    $nip = $this->input->post('nip')?$this->input->post('nip'):"";
        
        $this->session->set_userdata(array('nip' => $nip));    
        
        $data['list_data'] = $this->p->list_data($nip);
        $data['panel'] = $this->_setPanel($nip);
        $data['tampilkan_menu'] = true;
        $data['link'] = site_url().'/suami_istri/form_isian';
        
        if($this->input->post('page'))echo $data['list_data'];
        else $this->load->view('view_generik',$data);
    }

    function _getJurusan() {
        $this->db->order_by('nama', 'asc');
        $q = $this->db->get('jurusan');
        $list = '';
        if ($q->num_rows() > 0) {
            foreach ($q->result() as $row) {
                $list .= '"'.$row->nama.'",';
            }
            $list = substr($list, 0, -1);
        }
        return $list;
    }
    
    function _getNIP() {
        $this->db->order_by('nip', 'asc');
        $q = $this->db->get('pegawai');
        $list = '';
        if ($q->num_rows() > 0) {
            foreach ($q->result() as $row) {
                $list .= '"'.$row->nip.'",';
            }
            $list = substr($list, 0, -1);
        }
        return $list;
    }
    
    function _setRules() {
        return '
                    //set the rules for the field names
                    rules: {
                        nip: { required: true }
                    },
                    //set messages to appear inline
                    messages: {
                        nip: "NIP wajib diisi"
                    }
        ';
    }
    
    function _setPanel($nip) {
        $info_pegawai = '';
        if ($nip!="") {
            $this->db->select('gelar_depan, nama, gelar_belakang');
            $this->db->where(array('nip' => $nip));
            $this->db->or_where(array('nip_baru' => $nip));
            $query = $this->db->get('pegawai');
            if ($query->num_rows() > 0) {
                $r = $query->row();
                $info_pegawai = sprintf("%s %s %s", $r->gelar_depan, $r->nama, $r->gelar_belakang);
            } else {
                $info_pegawai = '-';
            }
        }
        $ret =  form_open('suami_istri').
                "<fieldset >
                 <table class=\"formTabel\" border=\"0\" align=\"center\" cellpadding=\"5\" cellspacing=\"1\">
                  <tr>
                    <td class=\"kolom\" valign=\"top\">NIP : <input type=\"text\" name=\"nip\" id=\"nip\" value=\"".$nip."\" /></td>
                    <td valign=\"top\"><input class=\"tombol\" type=\"submit\" name=\"button\" id=\"button\" value=\"Tampilkan\" /></td>
                    <td valign=\"top\"><div id=\"info_pegawai\">".$info_pegawai."</div></td>
                 </tr>
                 </table>
                 </fieldset>".
                 form_close();
        return $ret;        
    }
    
    function _setJsForm($additional_string="") {
        $ret = '
        <script type="text/javascript">
            $(function() {
                $("#nip").focus();'.
                $additional_string.
                '$("#btn_kembali").click( function() {
                    window.location = \''.base_url().'index.php/suami_istri\';
                });
                // validate contact form on keyup and submit
                $("form").validate({
                    '.$this->_setRules().'
                });
                $("form").submit(function() {
                    var nip = $("#nip").val();
                     $.ajax({
                       type: "POST",
                       url: "'.base_url().'index.php/suami_istri/cek_nip/"+nip,
                       success: function(msg) {
                         if (msg!=\'valid\') {
                             $.prompt(\'Maaf, NIP "\'+nip+\'" tidak terdaftar. Silahkan periksa lagi.\');
                            $("#nip").focus();
                            return false;
                         }
                       }
                    });
                });
            });
        </script>
        ';
        return $ret;
    }
    
    function form_isian() {
        if (!$this->session->userdata('username')) {
            $data['isLogin'] = FALSE;
            redirect("/login", "location");
        } else {
            $data['isLogin'] = TRUE;
            $data['username'] = $this->session->userdata('username');
            $data['role'] = $this->session->userdata('role');
        }
        
        $form_action = base_url().'index.php/suami_istri/simpan';
        $form_id = 'form_isian';
        
        $data['additional_js'] = $this->_setJsForm();
           
        $data['judul'] = 'INPUT DATA SUAMI / ISTRI';
        $data['list_data'] = $this->p->entry_data($form_id,$form_action);
        $this->load->view('view_generik', $data);
    }
    
    function simpan($is_update=false, $id='') {
        $this->load->model('Datum_model', 'd');
        if (!$this->input->post('nip')) {
            redirect('suami_istri/form_isian');
        } 
        
        $this->session->set_userdata(array('nip' => $this->input->post('nip')));
        
        $arr = $this->input->post('data')?$this->input->post('data'):"";
        
            $id_pegawai = $this->d->getData('idspg_pegawai', 'pegawai', array('nip_baru' => $this->input->post('nip')));
            $arr['id_pegawai'] = $id_pegawai!=false?$id_pegawai:$this->d->getData('idspg_pegawai', 'pegawai', array('nip' => $this->input->post('nip')));
        
        if ($arr['id_pegawai'] == false) {
            echo "<script>alert('NIP : ".$this->input->post('nip')." tidak terdaftar');                          
                          window.history.back();  
            </script>";
            return false;
        }
        if ($this->input->post('d')) {
            $a = array($this->input->post('y'), $this->input->post('m'), $this->input->post('d'));
            $arr['tgl_lahir'] = implode(TGL_SEPARATOR, $a);
        } 
        if ($this->input->post('dn')) {
            $a = array($this->input->post('yn'), $this->input->post('mn'), $this->input->post('dn'));
            $arr['tgl_nikah'] = implode(TGL_SEPARATOR, $a);
        } 
        
        $folder = './arsip/'.$arr['id_pegawai'];
        if(!is_dir($folder)){ mkdir($folder, 0777, true); chmod($folder, 0777); } 
        
        $config['upload_path'] = $folder;
        $config['allowed_types'] = 'gif|jpg|png';
        #$config['max_size'] = '100';
        #$config['max_width'] = '1024';
        #$config['max_height'] = '768';
        
        $this->load->library('upload', $config);
        
        if( $this->upload->do_upload('foto') )
        {
            $data = $this->upload->data();
            $arr['foto'] = $data['file_name'];
        }
            //echo $this->input->post('foto_sutri')."<pre>".print_r($arr,true);die;
            $this->p->simpan($arr, $is_update, $id);
            redirect('suami_istri/index/nip/'.$this->input->post('nip'));
        
    }
    
    function form_edit($id) {
        if (!$this->session->userdata('username')) {
            $data['isLogin'] = FALSE;
            redirect("/login", "location");
        } else {
            $data['isLogin'] = TRUE;
            $data['username'] = $this->session->userdata('username');
            $data['role'] = $this->session->userdata('role');
        }
        
        $this->load->model('Datum_model', 'd');
        $form_action = base_url().'index.php/suami_istri/simpan/true/'.$id;
        $form_id = 'form_suami_istri';  
        
        
        $this->db->where(array('id_suami_istri' => $id));
        $q = $this->db->get('suami_istri');
        if ($q->num_rows() > 0) {
            $arr = $q->row_array();
            
            $nip2 = $this->d->getData('nip_baru', 'pegawai', array('idspg_pegawai' => $arr['id_pegawai']));
            
            $arr['nip']                  = $nip2!=''?$nip2:$this->d->getData('nip', 'pegawai', array('idspg_pegawai' => $arr['id_pegawai']));
           
            $form_action = base_url().'index.php/suami_istri/simpan/true/'.$id;
            $form_id = 'form_suami_istri';
            
            $data['judul'] = 'UBAH DATA ANAK';
            $data['list_data'] = $this->p->entry_data($form_id,$form_action,$arr);
            $this->load->view('view_generik', $data);
        } else {
            redirect('suami_istri');
        }
    }


    function hapus($id) {
        if (!$this->session->userdata('username')) {
            $data['isLogin'] = FALSE;
            redirect("/login", "location");
        }
        $this->db->where('id_suami_istri', $id);
        echo $this->db->delete('suami_istri');
        
        //redirect('suami_istri', 'refresh');
    }
    
    function hapus_foto($id) {
        $this->db->where('id_suami_istri', $id);
        $this->db->update('suami_istri',array('foto' => ''));
        redirect('suami_istri/form_edit/'.$id);
    }
    
    function cek_nip($nip) {
        $this->load->model('Datum_model', 'd');
        $ret = $this->d->getData('nip', 'pegawai', array('nip' => $nip));
        $ret2 = $this->d->getData('nip_baru', 'pegawai', array('nip_baru' => $nip));
        if ($ret!=false || $ret2!=false) {
            echo 'valid';
        } else {
            echo 'ellol';
        }
    }
    
    
    function bisa_dihapus($id) {
        echo 'bisa';
    }
    
}
